package com.hopedove.callsystem.activity.call;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hopedove.base.BaseActivity;
import com.hopedove.callsystem.R;
import com.hopedove.callsystem.databinding.ActivitySavecallBinding;
import com.hopedove.callsystem.domain.net.CallTask;
import com.hopedove.callsystem.domain.net.QuerySJZD;
import com.hopedove.callsystem.entity.SJZDEntity;
import com.hopedove.net.ErrResponse;
import com.hopedove.net.OkResponse;
import com.hopedove.net.domain.Communication;
import com.hopedove.view.SimpleDialog;
import com.hopedove.view.TipsDialogFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;


public class SaveCallActivity extends BaseActivity implements OnClickListener {
    // 获取任务类型的数据字典id
    private static final String SJZDID_TASKLX = "BQTASKLX";

    /**
     * 存储任务类型的颜色
     **/
    private String mTaskLx = "";
    private ActivitySavecallBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySavecallBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initViewAndEvent();
        initData();
    }

    private void initViewAndEvent() {

        binding.callBtn.setOnClickListener(this);
        binding.cancelBtn.setOnClickListener(this);

        binding.monadNoEt.setOnKeyListener((v, keyCode, event) -> {
            if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                String monadNo = binding.monadNoEt.getText().toString().trim();
                String machineNo = "";
                if (monadNo.length() >= 4) {
                    machineNo = monadNo.substring(0, 4);
                    binding.machineNoEt.setText(machineNo);
                }

                return true;
            }
            return false;
        });

        binding.monadNoEt.setImeOptions(EditorInfo.IME_ACTION_SEARCH);

        binding.monadNoEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                binding.machineNoEt.setText("");
            }
        });
    }

    private void initData() {
        querySJZD(SJZDID_TASKLX);
    }


    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.callBtn) {
            String mMonadNo = binding.monadNoEt.getText().toString().trim();
            String mMachineNo = binding.machineNoEt.getText().toString().trim();

            if (TextUtils.isEmpty(mMonadNo)) {
                SimpleDialog.show(this, "三联单号不能为空，请重新扫描！");
                return;
            } else if (TextUtils.isEmpty(mMachineNo)) {
                SimpleDialog.show(this, "车号不能为空，请重新输入！");
                return;
            } else if (TextUtils.isEmpty(mTaskLx)) {
                SimpleDialog.show(this, "请选择任务类型！");
                return;
            }
            // 最后一个参数为是否是挡车工呼叫 1：是挡车工 2：保全工，这里传1
            callTask(mMonadNo, mMachineNo, mTaskLx, "", "1");
        } else if (id == R.id.cancelBtn) {
            finish();
        }
    }


    /**
     * 保全呼叫
     */
    private void callTask(String monadNo, String machineNo, String taskLx, String callTime, String HJLX) {
        showWait();
        Communication.asyncRequest(new CallTask(monadNo, machineNo, taskLx, callTime, HJLX), r -> {
            stopWait();
            if (r instanceof OkResponse) {
                TipsDialogFragment tipsDialog = TipsDialogFragment.showNewInstance(this, R.layout.callsys_tips_type_2, false);
                uiHandler.postDelayed(() -> {
                    TipsDialogFragment.dismissTipDialog(tipsDialog);
                    finish();
                }, 3000);
            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, ((ErrResponse) r).getErrText());
            }
        });
    }

    /**
     * 4.4. 查询数据字典
     */
    private void querySJZD(String SJZDID) {
        showWait();

        Communication.asyncRequest(new QuerySJZD(SJZDID), r -> {
            stopWait();

            if (r instanceof OkResponse) {
                JSONObject jsonObj = null;
                try {
                    jsonObj = new JSONObject(((OkResponse) r).getData());

                    //2018年9月25日  修改  保全呼叫页面是挡车工操作 ，去数据字典的时候取“DATADC”
                    JSONArray resultArray = jsonObj.optJSONArray("DATADC");
                    Gson gson = new Gson();
                    final List<SJZDEntity> tasks = gson.fromJson(resultArray.toString(), new TypeToken<List<SJZDEntity>>() {
                    }.getType());

                    // 初始化任务类型参数，很关键
                    // mTaskLx = tasks.get(0).KEYCODE;
                    for (int i = 0; i < tasks.size(); i++) {
                        SJZDEntity task = tasks.get(i);
                        final Button button = new Button(SaveCallActivity.this);

                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(150, LayoutParams.WRAP_CONTENT);
                        lp.setMargins(20, 0, 20, 0);// 设置边距
                        button.setLayoutParams(lp);
                        button.setText(task.SJXZ);
                        button.setBackground(getDrawableCompat(R.drawable.btn_corner_gray));

                        button.setTextColor(getColor(R.color.white));
                        button.setTextSize(30);
                        binding.taskLayout.addView(button);

                        final int index = i;
                        button.setOnClickListener(v -> {
                            for (int j = 0; j < tasks.size(); j++) {
                                Button button1 = (Button) binding.taskLayout.getChildAt(j);
                                button1.setBackground(getDrawableCompat(R.drawable.btn_corner_gray));
                            }
                            button.setBackground(getDrawableCompat(R.drawable.btn_corner_red));
                            // 赋值任务类型
                            mTaskLx = tasks.get(index).KEYCODE;
                        });
                    }
                } catch (JSONException e) {
                    SimpleDialog.show(this, "查询数据字典失败！");
                }

            } else if (r instanceof ErrResponse) {
                SimpleDialog.show(this, "查询数据字典失败！");
            }
        });

    }

}
